//
//  TemplateManager.m
//  FootPrint
//
//  Created by GeneChu on 4/13/13.
//  Copyright (c) 2013 alex tao. All rights reserved.
//

#import "TemplateManager.h"

@implementation TemplateManager

static TemplateManager * _sharedInstance = nil;

+ (TemplateManager*) sharedInstance
{
	if (_sharedInstance == nil) {
        _sharedInstance = [[TemplateManager alloc] init];
    }
	return _sharedInstance;
}

- (id)init
{
    self = [super init];
    if (self) {
        [self loadIndex];
        [self loadData];
    }
    return self;
}

- (void)dealloc
{
    [_realDict release];
    [_rootDict release];
    [_templateDict release];
    [super dealloc];
}

- (NSString *)rootDirectory
{
    if (nil == _rootDict) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *baseDir = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
        
        _rootDict = [[baseDir stringByAppendingPathComponent:@"Template"] copy];
    }
    
    if (![[NSFileManager defaultManager] fileExistsAtPath:_rootDict])
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:_rootDict
                                  withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    return _rootDict;
}

- (NSString*) templateIndexFilePath
{
    return [NSString stringWithFormat:@"%@/template.idx", [self rootDirectory]];
}

- (NSString*) templateFileForName:(NSString*)name
{
    return [NSString stringWithFormat:@"%@/%@", [self rootDirectory], name];
}

- (void) loadData
{
    if (nil == _realDict) {
        _realDict = [[NSMutableDictionary alloc] initWithCapacity:2];
    }
    
    NSArray * allNames = [_templateDict allKeys];
    for (NSString * name in allNames) {
        EventMessage * msg = [self eventForName:name];
        if (msg) {
            [_realDict setObject:msg forKey:name];
        }
    }
}

- (void) loadIndex
{
    _templateDict = [[NSMutableDictionary alloc] initWithContentsOfFile:[self templateIndexFilePath]];
    if (nil == _templateDict) {
        _templateDict = [[NSMutableDictionary alloc] initWithCapacity:4];
    }
}

- (void) saveIndex
{
    [_templateDict writeToFile:[self templateIndexFilePath] atomically:YES];
}


- (BOOL) eventExistForName:(NSString*)name
{
    return ([_templateDict objectForKey:name] != nil);
}

- (EventMessage*) eventForName:(NSString*)name
{
    NSString * path = [self templateFileForName:name];
    NSData * data = [NSData dataWithContentsOfFile:path];
    if (data) {
        return [EventMessage parseFromData:data];
    }
    return nil;
}

- (void) removeTamplate:(NSString*)name
{
    [_realDict removeObjectForKey:name];
    [_templateDict removeObjectForKey:name];
    NSString * path = [self templateFileForName:name];
    
    [[NSFileManager defaultManager] removeItemAtPath:path error:nil];
}

- (BOOL) saveTemplate:(EventMessage*)event forName:(NSString*)name
{
    if (nil == name) {
        name = @"Default";
    }
    NSData * data = [event data];
    if (nil == name || nil == data) {
        return NO;
    }
    
    [_realDict setObject:event forKey:name];
    
    NSString * path = [self templateFileForName:name];
    NSError * err = nil;
    if ([data writeToFile:path options:NSDataWritingAtomic error:&err]) {
        [_templateDict setObject:path forKey:name];
        
        [self saveIndex];
        return YES;
    }

    return NO;
}

- (NSArray*) allTemplate
{
    return [_realDict allValues];
}

@end
